In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
import pickle
import os
import tensorflow as tf
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
from sklearn.preprocessing import MinMaxScaler
from sklearn.utils import shuffle
from skimage.color import rgb2gray
from skimage.exposure import rescale_intensity, equalize_hist, equalize_adapthist
%matplotlib inline
# Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
#data
training_file = "../data/traffic_signs/train.p"
validation_file= "../data/traffic_signs/valid.p"
testing_file = "../data/traffic_signs/test.p"
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
# signnames
classes_df= pd.read_csv("./signnames.csv")
classes_series = pd.Series(classes_df.SignName, index=classes_df.ClassId)
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = X_train.shape[0]
# TODO: Number of validation examples
n_validation = X_valid.shape[0]
# TODO: Number of testing examples.
n_test = X_test.shape[0]
# TODO: What's the shape of an traffic sign image?
image_shape = X_train.shape[1:]
# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(y_test))
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?
# classes_df = pd.read_csv("./signnames.csv")
# classes_series = pd.Series(classes_df.SignName, index=classes_df.ClassId)
classes, counts=np.unique(y_train, return_counts=True)
def print_dataset_info():
print("data=")
print( [ "train:"+key+" ="+ str(len(train[key])) for key in list(train.keys())])
print( [ "valid:"+key+" ="+ str(len(valid[key])) for key in list(valid.keys())])
print( [ "test:"+key+" ="+ str(len(test[key])) for key in list(test.keys())])
print()
print("labels=", train["labels"].shape, train["labels"][0] )
print("coords=", train["coords"].shape, train["coords"][0] )
print("features=",train["features"].shape ,train["features"][0].shape,train["features"][0][0].shape,train["features"][0][0][0])
print("sizes=", train["sizes"].shape, train["sizes"][0])
print()
print("signnames=", classes_series.values)
print()
class_index=1
indexes = np.where(y_train==class_index), np.where(y_train==class_index)[0]
print("e.g. sings at class_index =", class_index,",'" , classes_series[class_index], "' image_at_indexes=", indexes[0])
#show dataset info
print_dataset_info()
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline
def plot_distribution(name="initial"):
bins = range(n_classes+1)
classes, counts=np.unique(y_train, return_counts=True)
max_samples_id = np.argmax(counts)
max_samples_bin_count= classes[max_samples_id]
fig = plt.figure(figsize=(12,5) , edgecolor="blue" )
# plt.suptitle('sample distribution')
plt.subplot(2,3,1).hist(y_train, bins, facecolor='b')
plt.title('Visualize "training" data dist')
plt.subplot(2,3,2).hist(y_valid, bins, facecolor='b')
plt.title('Visualize "valid" data dist')
plt.subplot(2,3,3 ).hist(y_test, bins, facecolor='b')
plt.title('Visualize "test" data dist')
plt.subplot(2,3,4 ).plot(classes, counts)
plt.title('"training" classes vs bins')
fig.tight_layout()
plt.savefig('./out_images/plot_distribution_'+name+'.png')
plt.show()
def plot_distribution_fake(y_train, name="initial"):
bins = range(n_classes+1)
classes, counts=np.unique(y_train, return_counts=True)
max_samples_id = np.argmax(counts)
max_samples_bin_count= classes[max_samples_id]
fig = plt.figure(figsize=(12,5) , edgecolor="blue" )
# plt.suptitle('sample distribution')
plt.subplot(2,3,1).hist(y_train, bins, facecolor='b')
plt.title('Visualize "training" data dist')
plt.subplot(2,3,4 ).plot(classes, counts)
plt.title('"training" classes vs bins')
fig.tight_layout()
plt.savefig('./out_images/plot_distribution_'+name+'.png')
plt.show()
#plot
plot_distribution(name="initial")
def show_images(dataset, squeeze=False, name=""):
images_to_show=len(dataset)
fig = plt.figure(figsize=(10,12))
print(name, ", count=",images_to_show)
for col,img in enumerate(dataset):
plt.subplot(1,images_to_show,col+1, xticks=[], yticks=[])
if squeeze:
plt.imshow(img.squeeze())
else:
plt.imshow(img)
fig.tight_layout()
plt.savefig('./out_images/img_'+name+'.png' )
plt.show()
def show_class_sample (dataset, images_to_show=9, squeeze=False, name=""):
for class_id in range(n_classes):
class_images = np.where(y_train == class_id)
images = X_train[np.random.choice(class_images[0], images_to_show)]
fig = plt.figure(figsize=(10,2))
for col,img in enumerate(images):
if col ==1:
print( (class_id +1), ":",classes_series[class_id])
plt.subplot(1,images_to_show,col+1, xticks=[], yticks=[])
if squeeze:
plt.imshow(img.squeeze())
else:
plt.imshow(img)
fig.tight_layout()
plt.savefig('./out_images/img_'+name+'_'+str(class_id)+'.png' )
plt.show()
#show each class sample
show_class_sample(X_train, 9, name="original")
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.
Other pre-processing steps are optional. You can try different techniques to see if it improves performance.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
import cv2
from numpy import newaxis
def normalize_img(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV);
img[:,:,0] = cv2.equalizeHist(img[:,:,0])
img = cv2.cvtColor(img, cv2.COLOR_YUV2BGR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(4,4))
img = clahe.apply(img)
a=0.1
b=0.9
img = a + ((img - np.amin(img))*(b-a))/(np.amax(img) - np.amin(img))
return np.expand_dims(img, axis=2)
def normalize(images):
return np.array([normalize_img(img) for img in images])
#normalize and show image
print(X_train[200].shape)
normalize_img(X_train[200]).shape
def transform_persp(img):
r,c = img.shape[:2]
rnd = np.random.randint(-2, 2)
pts1 = np.float32([[rnd,rnd],[r-rnd,rnd],[rnd,c-rnd],[r-rnd,c-rnd]])
pts2 = np.float32([[0,0],[r,0],[0,c],[r,c]])
#perspectiveTransform and warp
M = cv2.getPerspectiveTransform(pts1,pts2)
img = cv2.warpPerspective(img,M,(r,c))
return img
def eq_hist(img):
c = img.shape[2]
for j in range(c):
img[:, :, j] = cv2.equalizeHist(img[:, :, j])
return img
def rotate(img):
rnd = 25.0*np.random.rand() - 15
r,c = img.shape[:2]
M = cv2.getRotationMatrix2D((c/2,r/2), rnd, 1)
img = cv2.warpAffine(img, M, (c, r))
return img
def translation(img):
r,c = img.shape[:2]
rndx, rndy = np.random.randint(-3, 3, 2)
M = np.float32([[1, 0, rndx],[0, 1, rndy]])
img = cv2.warpAffine(img, M, (c,r))
return img
def augment(img):
img = transform_persp(img)
img = eq_hist(img)
img = rotate(img)
img = translation(img)
return img
def zoom(img):
rows,cols = img.shape[:2]
px = np.random.randint(-2, 2) # transform limits
pts1 = np.float32([[px,px],[rows-px,px],[px,cols-px],[rows-px,cols-px]]) # ending locations
pts2 = np.float32([[0,0],[rows,0],[0,cols],[rows,cols]]) # starting locations
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(rows,cols))
return dst
#test image augment and display augmented images
img=X_train[200]
print("transform_persp ",transform_persp(img).shape)
print("eq_hist ",eq_hist(img).shape)
print("rotate ",rotate(img).shape)
print("translation ",translation(img).shape)
print("zoom ",zoom(img).shape)
print("augment ",augment(img).shape)
img=augment(img)
print("normalize_img + augment",normalize_img(img).shape)
from tqdm import tqdm
def create_additional_for_class(images, diff_count=2500):
x_aug_class = []
counter=diff_count
while True:
for img in images:
if counter <= 0:
return x_aug_class
X_aug_imgs = augment(img)
x_aug_class.append(X_aug_imgs)
counter = counter - 1
def create_additional_images(X_orig, y_orig, max_count=5000):
unique, counts = np.unique(y_orig, return_counts=True)
X_aug = []
y_aug = []
for cls, cls_count in tqdm(list(zip(unique, counts)), "create additional images " ):
diff_count = max_count - cls_count
if diff_count > 1 :
X_class = X_orig[np.where(y_orig == cls)[0]]
X_class_aug = create_additional_for_class(X_class, diff_count)
X_aug += X_class_aug
y_aug += [cls for _ in range( len(X_class_aug))]
# print(cls_count," diff_count=", diff_count, ", X_class_aug=", np.array(X_class_aug).shape , " class ", cls, "= '", classes_series[cls],"'")
return X_aug, y_aug
# X_aug, y_aug = create_additional_images(X_train, y_train, max_count=5000)
# X_valid_aug, y_valid_aug = create_additional_images(X_valid, y_valid, max_count=750)
# X_test_aug, y_test_aug = create_additional_images(X_test, y_test, max_count=2500)
# # show_images(X_aug, squeeze=False)
# print("new augmented images= X_aug =",np.array(X_aug).shape, " y_aug=",np.array(y_aug).shape)
# print("new augmented images= X_valid_aug = ",np.array(X_valid_aug).shape, " y_valid_aug=",np.array(y_valid_aug).shape)
# print("new augmented images= X_test_aug = ",np.array(X_test_aug).shape, " y_test_aug=",np.array(y_test_aug).shape)
# show_class_sample(np.array(X_aug), 9, name="fake")
X_aug, y_aug = create_additional_images(X_train, y_train, max_count=500)
# X_aug, y_aug = create_additional_images(X_train, y_train, max_count=5000)
# show_images(X_aug, squeeze=False)
print("new augmented images=",np.array(X_aug).shape, " y_aug=",np.array(y_aug).shape)
show_class_sample(np.array(X_aug), 9, name="fake")
# #concat augmented images with original X_train
X_train_use = np.concatenate([X_train, np.array(X_aug)])
y_train_use = np.concatenate([y_train, np.array(y_aug)])
print("X_train_norm=",X_train_use.shape, " y_train_use=",y_train_use.shape)
#normlize
y_train_norm = y_train_use
X_train_norm = normalize(X_train_use)
X_valid_norm = normalize(X_valid )
X_test_norm = normalize(X_test)
print("X_train_norm=",X_train_norm.shape, " X_valid_norm=",X_valid_norm.shape)
print("Show normalize X_train_norm")
print(X_train_norm.shape)
show_class_sample(X_train_norm, 9, name="normalized")
# equalize_adapthist??
# #shuffle and set y_train_norm to X_train
X_train, y_train = shuffle(X_train_norm, y_train_norm)
X_valid, X_test = X_valid_norm, X_test_norm
# ### Define your architecture here.
# ### Feel free to use as many code cells as needed.
# import tensorflow as tf
# from tensorflow.contrib.layers import flatten
# def t_sign_net(x, keep_prob, sigma=0.1, mu=0):
# ################## CONV2D_LAYER_1 ################
# input_shape=x.shape
# W1 = tf.Variable(tf.truncated_normal((5, 5, 1, 6), mu, sigma))
# b1 = tf.Variable(tf.zeros(6))
# strides = [1, 1, 1, 1]
# cnv_layer_1 = tf.nn.conv2d(x, W1, strides, 'VALID') + b1
# cnv_layer_1 = tf.nn.relu(cnv_layer_1)
# print("CONV2D_LAYER_1: input_shape=32x32x1, output=28x28x6 "
# , ", input_s=", input_shape
# , ", output_s=", cnv_layer_1.get_shape()
# , ", activation=relu, padding=VALID,"
# , ", strides=", strides
# , ", ksize=", (5, 5)
# )
# #CONV2D_LAYER_1 input_shape=32x32x1, output=28x28x6.
# ################## CONV2D_LAYER_1 ################
# ################## MAX_POOL_1 ################
# input_shape = cnv_layer_1.get_shape()
# ksize = [1, 2, 2, 1]
# strides = [1, 2, 2, 1]
# maxpool_layer_1 = tf.nn.max_pool(cnv_layer_1, ksize, strides, 'VALID')
# maxpool_layer_1 = tf.nn.relu(maxpool_layer_1)
# print("MAX_POOL_1: input_shape=28x28x6, output=14x14x6 "
# , ", input_s=", input_shape
# , ", output_s=", maxpool_layer_1.get_shape()
# , ", activation=relu, padding=VALID,"
# , ", strides=", strides
# , ", ksize=", ksize
# )
# # MAX_POOL_1: input_shape=28x28x6, output=14x14x6
# ################## MAX_POOL_1 ################
# ################## CONV2D_LAYER_2 ################
# input_shape=maxpool_layer_1.get_shape()
# F_W_2 = tf.Variable(tf.truncated_normal((5, 5, 6, 16), mu, sigma))
# F_b_2 = tf.Variable(tf.zeros(16))
# strides = [1, 1, 1, 1]
# cnv_layer_2 = tf.nn.conv2d(maxpool_layer_1, F_W_2, strides, 'VALID') + F_b_2
# cnv_layer_2 = tf.nn.relu(cnv_layer_2)
# print("CONV2D_LAYER_2: input_shape=14x14x6, output = 10x10x16"
# , ", input_s=", input_shape
# , ", output_s=", cnv_layer_2.get_shape()
# , ", activation=relu, padding=VALID,"
# , ", strides=", strides
# , ", ksize=", ksize
# )
# # CONV2D_LAYER_2: input_shape=14x14x6, output = 10x10x16
# ################## CONV2D_LAYER_2 ################
# ################## MAX_POOL_2 ################
# input_shape = cnv_layer_2.get_shape()
# ksize = [1, 2, 2, 1]
# strides = [1, 2, 2, 1]
# maxpool_layer_2 = tf.nn.max_pool(cnv_layer_2, ksize, strides, 'VALID')
# maxpool_layer_2 = tf.nn.relu(maxpool_layer_2)
# print("MAX_POOL_2: input_shape=10x10x16, output = 5x5x16 "
# , ", input_s=", input_shape
# , ", output_s=", maxpool_layer_2.get_shape()
# , ", activation=relu, padding=VALID,"
# , ", strides=", strides
# , ", ksize=", ksize
# )
# # MAX_POOL_2: input_shape=10x10x16, output = 5x5x16.
# ################## MAX_POOL_2 ################
# ################## FULLY_CONNECTED_1 ################
# input_shape = maxpool_layer_2.get_shape()
# fc_layer_1 = tf.contrib.layers.flatten(maxpool_layer_2)
# F_W_3 = tf.Variable(tf.truncated_normal((400, 240), mu, sigma))
# F_b_3 = tf.Variable(tf.zeros(240))
# fc_layer_1 = tf.nn.bias_add(tf.matmul(fc_layer_1, F_W_3), F_b_3)
# fc_layer_1 = tf.nn.relu(fc_layer_1)
# # FULLY_CONNECTED_1: input_shape=10x10x16=400, output =240
# print("FULLY_CONNECTED_1: input_shape=10x10x16, flatten=400, output =240 "
# , ", input_s=", input_shape
# , ", output_s=", fc_layer_1.get_shape()
# , ", activation=relu, padding=VALID,"
# , ", strides=", strides
# , ", ksize=", ksize
# )
# ################## FULLY_CONNECTED_1 ################
# ################## FULLY_CONNECTED_2 ################
# input_shape = fc_layer_1.get_shape()
# F_W_4 = tf.Variable(tf.truncated_normal((240, 240), mu, sigma))
# F_b_4 = tf.Variable(tf.zeros(240))
# fc_layer_2 = tf.nn.bias_add(tf.matmul(fc_layer_1, F_W_4), F_b_4)
# fc_layer_2 = tf.nn.relu(fc_layer_2)
# # dropout
# fc_layer_2 = tf.nn.dropout(fc_layer_2, keep_prob)
# # FULLY_CONNECTED_2: input_shape=240, output =240
# print("FULLY_CONNECTED_2: input_shape=240, output =240 "
# , ", input_s=", input_shape
# , ", output_s=", fc_layer_2.get_shape()
# , ", activation=relu, padding=VALID, dropout"
# )
# ################## FULLY_CONNECTED_2 ################
# ################## FULLY_CONNECTED_3 ################
# input_shape = fc_layer_2.get_shape()
# F_W_5 = tf.Variable(tf.truncated_normal((240, 43), mu, sigma))
# F_b_5 = tf.Variable(tf.zeros(43))
# logits = tf.nn.bias_add(tf.matmul(fc_layer_2, F_W_5), F_b_5)
# # FULLY_CONNECTED_3: input_shape = 240. Output = 43.
# print("FULLY_CONNECTED_2: input_shape=240, output=43 "
# , ", input_s=", input_shape
# , ", output_s=", logits.get_shape()
# )
# ################## FULLY_CONNECTED_3 ################
# return logits
# print("================= model ======================= ")
# kp = tf.placeholder(tf.float32)
# x = tf.placeholder(tf.float32, (None, 32, 32, 1))
# t_sign_net(x, kp)
# print("================= model ======================= ")
def t_sign_net(x, keep_prob, sigma=0.1, mu=0):
# CONV2D_LAYER_1 ################ ################ ################
input_shape=x.shape
W1 = tf.Variable(tf.truncated_normal((5, 5, 1, 16), mu, sigma))
b1 = tf.Variable(tf.zeros(16))
strides = [1, 1, 1, 1]
cnv_layer_1 = tf.nn.conv2d(x, W1, strides, 'VALID') + b1
cnv_layer_1 = tf.nn.relu(cnv_layer_1)
print("CONV2D_LAYER_1: "#input_shape=32x32x1, output=28x28x6 "
, ", input_s=", input_shape
, ", output_s=", cnv_layer_1.get_shape()
, ", activation=relu, padding=VALID,"
, ", strides=", strides
, ", ksize=", (5, 5)
)
#CONV2D_LAYER_1 input_shape=32x32x1, output=28x28x6.
################## CONV2D_LAYER_1 ################
#MAX_POOL_1 ################ ################ ################
input_shape = cnv_layer_1.get_shape()
ksize = [1, 2, 2, 1]
strides = [1, 2, 2, 1]
maxpool_layer_1 = tf.nn.max_pool(cnv_layer_1, ksize, strides, 'VALID')
maxpool_layer_1 = tf.nn.relu(maxpool_layer_1)
print("MAX_POOL_1: "#input_shape=28x28x6, output=14x14x6 "
, ", input_s=", input_shape
, ", output_s=", maxpool_layer_1.get_shape()
, ", activation=relu, padding=VALID,"
, ", strides=", strides
, ", ksize=", ksize
)
# MAX_POOL_1: input_shape=28x28x6, output=14x14x6
################## MAX_POOL_1 ################
################## CONV2D_LAYER_2 ################
input_shape=maxpool_layer_1.get_shape()
F_W_2 = tf.Variable(tf.truncated_normal((5, 5, 16, 32), mu, sigma))
F_b_2 = tf.Variable(tf.zeros(32))
strides = [1, 1, 1, 1]
cnv_layer_2 = tf.nn.conv2d(maxpool_layer_1, F_W_2, strides, 'VALID') + F_b_2
cnv_layer_2 = tf.nn.relu(cnv_layer_2)
print("CONV2D_LAYER_2: "#input_shape=14x14x6, output = 10x10x16"
, ", input_s=", input_shape
, ", output_s=", cnv_layer_2.get_shape()
, ", activation=relu, padding=VALID,"
, ", strides=", strides
, ", ksize=", ksize
)
# CONV2D_LAYER_2: input_shape=14x14x6, output = 10x10x16
################## CONV2D_LAYER_2 ################
################## MAX_POOL_2 ################
input_shape = cnv_layer_2.get_shape()
ksize = [1, 2, 2, 1]
strides = [1, 2, 2, 1]
maxpool_layer_2 = tf.nn.max_pool(cnv_layer_2, ksize, strides, 'VALID')
maxpool_layer_2 = tf.nn.relu(maxpool_layer_2)
print("MAX_POOL_2: "#input_shape=10x10x16, output = 5x5x16 "
, ", input_s=", input_shape
, ", output_s=", maxpool_layer_2.get_shape()
, ", activation=relu, padding=VALID,"
, ", strides=", strides
, ", ksize=", ksize
)
# MAX_POOL_2: input_shape=10x10x16, output = 5x5x16.
################## MAX_POOL_2 ################
######################################### new #########################################
################## CONV2D_LAYER_3 ################
input_shape=maxpool_layer_2.get_shape()
F_W_2 = tf.Variable(tf.truncated_normal((3, 3, 32, 128), mu, sigma))
F_b_2 = tf.Variable(tf.zeros(128))
strides = [1, 1, 1, 1]
cnv_layer_3 = tf.nn.conv2d(maxpool_layer_2, F_W_2, strides, 'VALID') + F_b_2
cnv_layer_3 = tf.nn.relu(cnv_layer_3)
print("CONV2D_LAYER_2: input_shape=14x14x6, output = 10x10x16"
, ", input_s=", input_shape
, ", output_s=", cnv_layer_3.get_shape()
, ", activation=relu, padding=VALID,"
, ", strides=", strides
, ", ksize=", ksize
)
# CONV2D_LAYER_3: input_shape=14x14x6, output = 10x10x16
################## CONV2D_LAYER_3 ################
################## MAX_POOL_3 ################
input_shape = cnv_layer_3.get_shape()
ksize = [1, 2, 2, 1]
strides = [1, 1, 1, 1]
maxpool_layer_3 = tf.nn.max_pool(cnv_layer_3, ksize, strides, 'VALID')
maxpool_layer_3 = tf.nn.relu(maxpool_layer_3)
print("MAX_POOL_2: "#input_shape=10x10x16, output = 5x5x16 "
, ", input_s=", input_shape
, ", output_s=", maxpool_layer_3.get_shape()
, ", activation=relu, padding=VALID,"
, ", strides=", strides
, ", ksize=", ksize
)
# MAX_POOL_2: input_shape=10x10x16, output = 5x5x16.
################## MAX_POOL_3 ################
######################################### new #########################################
################## FULLY_CONNECTED_1 ################
input_shape = maxpool_layer_3.get_shape()
fc_layer_1 = tf.contrib.layers.flatten(maxpool_layer_3)
F_W_3 = tf.Variable(tf.truncated_normal((512, 240), mu, sigma))
F_b_3 = tf.Variable(tf.zeros(240))
fc_layer_1 = tf.nn.bias_add(tf.matmul(fc_layer_1, F_W_3), F_b_3)
fc_layer_1 = tf.nn.relu(fc_layer_1)
# FULLY_CONNECTED_1: input_shape=10x10x16=400, output =240
print("FULLY_CONNECTED_1: "#input_shape=10x10x16, flatten=400, output =240 "
, ", input_s=", input_shape
, ", output_s=", fc_layer_1.get_shape()
, ", activation=relu, padding=VALID,"
, ", strides=", strides
, ", ksize=", ksize
)
################## FULLY_CONNECTED_1 ################
################## FULLY_CONNECTED_2 ################
input_shape = fc_layer_1.get_shape()
F_W_4 = tf.Variable(tf.truncated_normal((240, 240), mu, sigma))
F_b_4 = tf.Variable(tf.zeros(240))
fc_layer_2 = tf.nn.bias_add(tf.matmul(fc_layer_1, F_W_4), F_b_4)
fc_layer_2 = tf.nn.relu(fc_layer_2)
# dropout
fc_layer_2 = tf.nn.dropout(fc_layer_2, keep_prob)
# FULLY_CONNECTED_2: input_shape=240, output =240
print("FULLY_CONNECTED_2: "#input_shape=240, output =240 "
, ", input_s=", input_shape
, ", output_s=", fc_layer_2.get_shape()
, ", activation=relu, padding=VALID, dropout"
)
################## FULLY_CONNECTED_2 ################
################## FULLY_CONNECTED_3 ################
input_shape = fc_layer_2.get_shape()
F_W_5 = tf.Variable(tf.truncated_normal((240, 43), mu, sigma))
F_b_5 = tf.Variable(tf.zeros(43))
logits = tf.nn.bias_add(tf.matmul(fc_layer_2, F_W_5), F_b_5)
# FULLY_CONNECTED_3: input_shape = 240. Output = 43.
print("FULLY_CONNECTED_2: "#input_shape=240, output=43 "
, ", input_s=", input_shape
, ", output_s=", logits.get_shape()
)
################## FULLY_CONNECTED_3 ################
return logits
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
EPOCHS = 75
BATCH_SIZE = 128
rate = 0.001
mu = 0
sigma = 0.1
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32)
one_hot_y = tf.one_hot(y, 43)
learning_rate = tf.placeholder(tf.float32)
logits = t_sign_net(x, keep_prob, sigma=sigma, mu=mu)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate)
training_operation = optimizer.minimize(loss_operation)
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
total_loss = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy, loss = sess.run([accuracy_operation, loss_operation], feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0})
total_accuracy += accuracy * len(batch_x)
total_loss += loss * len(batch_x)
return (total_accuracy / num_examples, total_loss / num_examples)
saver = tf.train.Saver()
# X_train, y_train = shuffle(X_train_use, y_train_use)
folder="./"
# if not os.path.exists(folder):
# os.mkdir(folder)
train_loss_history = []
train_accuracy_history = []
valid_loss_history = []
valid_accuracy_history = []
with tf.Session() as sess:
if os.path.exists(folder+'model.data-00000-of-00001'):
saver.restore(sess, tf.train.latest_checkpoint(folder))
print ('restored')
else:
sess.run(tf.global_variables_initializer())
num_examples = len(X_train)
print("Training...")
for i in range(EPOCHS):
rate = 0.001 if i < 8 else 0.0004
X_train, y_train = shuffle(X_train, y_train)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train[offset:end], y_train[offset:end]
sess.run(training_operation, feed_dict={x: batch_x,
y: batch_y,
keep_prob: 0.5,
learning_rate: rate
})
valid_accuracy, valid_loss = evaluate(X_valid, y_valid)
valid_accuracy_history.append(valid_accuracy)
valid_loss_history.append(valid_loss)
train_accuracy, train_loss = evaluate(X_train, y_train)
train_accuracy_history.append(train_accuracy)
train_loss_history.append(train_loss)
print("EPOCH {} ...".format(i+1), end='')
print(" [train-acc = {:.3f}, train-loss = {:.3f}]".format(train_accuracy, train_loss), end='')
print(" [valid-acc = {:.3f}, valid-loss = {:.3f}]".format(valid_accuracy, valid_loss) )
if i > 0 and i % 10 == 0:
saver.save(sess, folder+'model')
print('model saved')
# if loss_valid < 0.01:
# break
saver.save(sess, folder+'model')
print('model saved')
fig = plt.figure()
loss_plot = plt.subplot(2,1,1)
loss_plot.set_title('loss')
loss_plot.plot(train_loss_history, 'y', label='training loss')
loss_plot.plot(valid_loss_history, 'b', label='validation loss')
loss_plot.set_xlim([0, EPOCHS])
loss_plot.legend(loc = 1)
accuracy_plot = plt.subplot(2,1,2)
accuracy_plot.set_title('accuracy')
accuracy_plot.plot(train_accuracy_history, 'y', label='training accuracy')
accuracy_plot.plot(valid_accuracy_history, 'b', label='validation accuracy')
accuracy_plot.set_xlim([0, EPOCHS])
accuracy_plot.legend(loc = 4)
fig.tight_layout()
plt.savefig('./out_images/accuracy_loss.png')
plt.show()
# X_test = normalize(X_test)
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
test_accuracy, _ = evaluate(X_test_norm, y_test)
print("Test Accuracy = {:.3f}".format(test_accuracy))
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
## Load the images and plot them here.
### Feel free to use as many code cells as needed.
import cv2
import matplotlib.pyplot as plt
import os
import glob
def load_test_image(path = r"./test_images/*.jpg"):
dim = (32,32)
test_images_a = []
test_labels_a = []
test_names_a = []
for img_path in glob.glob(path):
img_path_w_ext = os.path.basename(img_path)
filename, file_extension = os.path.splitext(img_path_w_ext)
f_class_name = ''.join(ch for ch in filename if ch.isdigit())
img = cv2.imread(img_path)
img = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
test_images_a.append(img)
test_names_a.append(filename)
test_labels_a.append(int(f_class_name))
print("imgage=" , img_path_w_ext , ", cls=",classes_series[ int(f_class_name)] )
return test_images_a, test_labels_a,test_names_a
# for index, label in enumerate(test_labels_a):
# print("(class=", label ,") ...", classes_series[ int(label)])#, ", shape=", img.shape)
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
# normalize new test data
def predit_test_images(images):
print()
test_images = images #normalize(images)
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint(folder))
prediction = tf.argmax(logits, 1)
test_prediction = sess.run(
prediction,
feed_dict={x: test_images, keep_prob: 1.0})
counter=0;
print(test_prediction, "==", test_names_a)
for index, prediction in zip(test_labels_a,test_prediction):
if int(prediction) == int(index):
predicted="CORRECT"
else:
predicted="WRONG"
print()
pred=" * prediction: {:} = ground_truth: {:}".format( int(prediction) , int(index))
pred_label=" * (prediction: {} = ground_truth: {})".format( classes_series[ int(prediction)] , classes_series[ int(index)])
print(" * Prediction for: "+ test_names_a[counter] +".jpg")
print(" * prediction:"+predicted)
print(pred)
print(pred_label)
counter =counter + 1
test_images_a, test_labels_a, test_names_a =load_test_image()
test_images = np.asarray(test_images_a)
test_labels = np.asarray(test_labels_a)
show_images(test_images, name="new-images-for-testing")
test_images_norm = normalize(test_images)
predit_test_images(test_images_norm)
### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
def predit_test_images_softwmax(images, labels):
X_test_images = images #normalize(images)
y_test_images = labels
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint(folder))
test_accuracy, test_loss = evaluate(X_test_images, y_test_images)
softmax_prob = sess.run(tf.nn.softmax(logits), feed_dict={x: X_test_images, keep_prob: 1.0})
top5_prob = sess.run(tf.nn.top_k(softmax_prob, k = 5))
return top5_prob
print("New Test Set Accuracy = {:.3f}".format(test_accuracy))
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
probabilities, predict_classes = predit_test_images_softwmax(test_images_norm, test_labels)
index = np.arange(5)
# print(probabilities, predict_classes)
counter=0
for img, label in zip(test_images_norm, test_labels):
print()
pred_labels= [ classes_series[int(predict)] for predict in probabilities[counter]]
print("* Probabilites for: ", test_names_a[counter])
print("* Predicted: " , probabilities[counter])
print("* Predicted labels: ",pred_labels)
print("* Actual: ", label , " '" + classes_series[int(label)] + "'" , )
# print(label, classes_series[int(label)])
# print(label, "=",predict_classes[counter] , "=>", probabilities[counter])
plt.figure(figsize = (12, 2.5))
plt.subplot(1, 2, 1)
plt.imshow(img.squeeze(), cmap = 'gray')
plt.xticks(np.array([]))
plt.yticks(np.array([]))
img_top5_prbs=probabilities[counter]
cls_img=predict_classes[counter]
img_top5_cls = [classes_series[int(cls_img[i])] for i in index]
plt.subplot(1, 2, 2)
plt.barh(index, img_top5_prbs, align='center')
plt.yticks(index, img_top5_cls )
#plt.show()
fig.tight_layout()
plt.savefig('./out_images/test_image_prediction_'+test_names_a[counter]+'.png')
plt.show()
counter += 1
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.
Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.
For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.
Your output should look something like this (above)
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry
def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
# Here make sure to preprocess your image_input in a way your network expects
# with size, normalization, ect if needed
# image_input =
# Note: x should be the same name as your network's tensorflow data placeholder variable
# If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
featuremaps = activation.shape[3]
plt.figure(plt_num, figsize=(15,15))
for featuremap in range(featuremaps):
plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
if activation_min != -1 & activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
elif activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
elif activation_min !=-1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
else:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")